"use strict";
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.wxuserInfo){
      typeof cb == "function" && cb()
    }else{
      //调用登录接口
      //that.requestUserInfo(cb)
      wx.getStorage({
        key: 'wxuserInfo',
        success: function(res) {
          console.log('读取缓存数据',res)
          that.globalData.wxuserInfo = res.data
          typeof cb == "function" && cb()
        },
        fail:function(){
           console.log('不存在缓存数据')
           that.requestUserInfo(cb)
        }
      })
    }
  },
  requestUserInfo:function(cb){
    var openid;
    var that = this
    wx.login({
        success: function (res) {
          var d=that.globalData;
          var l='https://api.weixin.qq.com/sns/jscode2session?appid='+d.appid+'&secret='+d.secret+'&js_code='+res.code+'&grant_type=authorization_code';
          wx.request({    
              url: l,    
              data: {},    
              method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT    
              // header: {}, // 设置请求的 header    
              success: function(res){  
                console.log('jscode2session',res) 
                  openid=res.data.openid
                res.userInfo={};
                res.userInfo.openid = openid
                that.globalData.wxuserInfo = res.userInfo
                typeof cb == "function" && cb(res.userInfo)
                //   wx.getUserInfo({
                //   success: function (res) {
                //     res.userInfo.openid = openid
                //     that.globalData.wxuserInfo = res.userInfo
                //     wx.setStorageSync('wxuserInfo', res.userInfo)
                //     typeof cb == "function" && cb(that.globalData.wxuserInfo)
                //   }
                // })
              }    
          });   
          
        }
      })
  },
  globalData:{
    userInfo:null,
    wxuserInfo:null,
    inputValue:null,
    appid:'wxf54dea83d4b4ba11',//appid需自己提供，此处的appid我随机编写  
    secret:'253c4572f948125d547624e1e89e958e'//secret需自己提供，此处的secret我随机编写  
  }
})